package com.jcbase.core.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.RecursiveTask;

import com.jcbase.core.util.UUIDHexgenerator;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**
 * @category 使用fork Join操作数据，保存优惠券，多任务形式
 * 
 * @author yiz
 * @date 2016年8月11日 下午4:08:58
 * @version 1.0.0 
 */
public class SaveCouponTask extends RecursiveTask<Integer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3089555479866263178L;

	private List<String> couponNos;

	private int start;

	private int end;

	private int threshold;
	private String rule_id;
	private Integer status;
	private Integer coupon_type;

	public SaveCouponTask(List<String> couponNos, int start, int end, int threshold, String rule_id, Integer status,
			Integer coupon_type) {
		this.couponNos = couponNos;
		this.start = start;
		this.end = end;
		this.threshold = threshold;
		this.rule_id = rule_id;
		this.status = status;
		this.coupon_type = coupon_type;
	}

	@Override
	protected Integer compute() {
		int result = 0;
		if (end - start <= threshold) {
			result = this.saveCoupon(couponNos, start, end, rule_id, status, coupon_type);//保存
		} else {
			int middle = (end + start) / 2;
			SaveCouponTask leftSaveTask = new SaveCouponTask(couponNos, start, middle, threshold, rule_id, status,
					coupon_type);
			SaveCouponTask rightSaveTask = new SaveCouponTask(couponNos, middle + 1, end, threshold, rule_id, status,
					coupon_type);
			invokeAll(leftSaveTask, rightSaveTask);
		}
		return result;
	}

	private int saveCoupon(List<String> couponNos, int start, int end, String rule_id, Integer status2,
			Integer coupon_type2) {
		List<Record> recordList = new ArrayList<>();
		Record record = null;
		for (int i = start; i <= end; i++) {
			record = new Record();
			record.set("id", UUIDHexgenerator.generate()).set("rule_id", rule_id).set("coupon_no", couponNos.get(i))
					.set("status", status).set("coupon_type", coupon_type).set("create_time", new Date())
					.set("update_time", new Date());
			recordList.add(record);
		}
		int[] result = Db.batchSave("risebd_coupon", recordList, recordList.size());
		if (result.length > 0) {
			return 1;
		} else {
			return 0;
		}
	}
}
